package cn.isjinhao.se.sql.function.handler.string;

import cn.isjinhao.se.sql.function.evaluator.FunctionEvaluator;
import cn.isjinhao.se.sql.function.handler.AbstractFunctionHandler;
import cn.isjinhao.se.sql.grammar.CurdStatement;
import cn.isjinhao.se.sql.grammar.statement.CurdStatementType;
import cn.isjinhao.se.sql.grammar.statement.Function;
import cn.isjinhao.se.sql.grammar.statement.Identifier;
import cn.isjinhao.se.sql.grammar.statement.Literal;
import cn.isjinhao.se.structure.ResultType;

import java.util.List;

/**
 * @Author ISJINHAO
 * @Date 2021/7/28 19:11
 */
public class ReplaceHandler extends AbstractFunctionHandler {

    public ReplaceHandler(FunctionEvaluator functionEvaluator) {
        super(functionEvaluator);
    }

    @Override
    public String functionName() {
        return "replace";
    }

    @Override
    public ResultType resultType() {
        return ResultType.STRING;
    }

    @Override
    public void staticCheck(Function function, CurdStatementType type) {
        checkParameterSize(function, 3);
        List<CurdStatement> parameterList = function.getParameterList();
        checkType(parameterList.get(0), function, Literal.class, Identifier.class);
        checkType(parameterList.get(1), function, Literal.class);
        checkType(parameterList.get(2), function, Literal.class);
    }

    @Override
    public Object evaluate(Function function, CurdStatementType type, Object... parameters) {

        String str = (String) parameters[0];
        String oldSeg = (String) parameters[1];
        String newSeg = (String) parameters[2];

        return str.replaceAll(oldSeg, newSeg);
    }

}
